import React, { useState, useEffect } from "react";
import { View, Button, Input, Image, Text } from "@tarojs/components";
import { loginData, toast, goBack } from "@/utils/utils";
import { fakeEditUserInfo } from "@/server/login";
import { upload } from "@/utils/upload";

import "./index.scss";
import Taro from "@tarojs/taro";
export default ({ }) => {
  const [userInfo, setUserInfo] = useState({
    profile: "",
    username: ""
  });
  useEffect(() => {
    setUserInfo(loginData() || {});
  }, []);
  const { profile, username, id } = userInfo;
  const onChooseAvatar = e => {
    setUserInfo({
      ...userInfo,
      profile: e.detail.avatarUrl
    });
  };
  return (
    <View className="information_box">
      <View className="userinfo">
        <View className="change_box">
          <Button
            open-type="chooseAvatar"
            onChooseAvatar={onChooseAvatar} // 在taro中使用的是onChooseAvatar
            className="change_btn"
          ></Button>
          <Image className="userinfo-avatar" src={profile} mode="cover"></Image>
        </View>
        <View>
          <Input
            className="nick-name-input"
            placeholder="请输入昵称"
            value={username}
            onInput={e => {
              console.log(e);
              setUserInfo({
                ...userInfo,
                username: e.detail.value
              });
            }}
          />
        </View>
        <View
          onClick={async () => {
            if (profile && username) {
              console.log(username);
              let image = await upload([profile], {
                img: [profile]
              });
              image = image.img[0];
              console.log(image, 111)
              fakeEditUserInfo({
                id: id,
                username: username,
                profile: image
              }).then(val => {
                toast("修改成功");
                Taro.setStorageSync("userInfo", {
                  ...userInfo,
                  username: username,
                  profile: image
                });
                setTimeout(() => {
                  goBack();
                }, 1000);
              });
            }
            else {
              toast('请填写完整信息')
            }
          }}
          className="content__btn"
        >
          确认修改
        </View>
        <View
          onClick={() => {
            goBack();
          }}
          className="gobackBtn"
        >
          取消
        </View>
      </View>
    </View >
  );
};
